<template>
  <el-card>
    <div class="table">

      <!-- 表格 -->
      <el-table v-loading="loading" :data="commodityList" style="width: 100%">

        <el-table-column v-for="item in commodityTableLabel" :key="item.prop" :label="item.label" :prop="item.prop"
          :width="item.width" :sortable="item.sortable" />
        <!-- 商品价格 -->
        <el-table-column label="商品价格/元">
          <template v-slot="scope">
            {{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <!-- 商品类别 -->
        <el-table-column label="商品类别">
          <template v-slot="scope">
            <el-tag v-if="currentCategoryList.length > scope.$index" type="info">
              {{ currentCategoryList[scope.$index].categoryName }}
            </el-tag>
          </template>
        </el-table-column>
        <!--  商品状态 -->
        <el-table-column :filters="[{ text: '上架', value: 1 }, { text: '已下架', value: 0 }]" prop="status" label="商品状态"
          :filter-method="filterTag">
          <template v-slot="scope">
            <el-tag size="small" v-if="scope.row.status === 1" type="success">上架</el-tag>
            <el-tag size="small" v-else-if="scope.row.status === 0" type="warning">已下架</el-tag>
          </template>
        </el-table-column>
        <!-- 相关操作 -->
        <el-table-column fixed="right" label="操作">
          <template v-slot="scope">
            <el-button type="primary" size="small"
              @click="() => { getCommodityDetail(scope.$index); dialogVisible = true; }">详情
            </el-button>
            <el-button type="danger" size="small" @click="offShelf(scope.row)">下架</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination background layout="prev, pager, next" :total="config.total" class="pager mt-4"
        @current-change="changePage" :page-size="config.size" />
    </div>
  </el-card>

  <!-- 查看商品详情的模态框 -->
  <el-dialog v-model="dialogVisible" title="查看商品详情" width="50%">

    <!-- 商品表单，也可发起修改 -->
    <div class="commodity-form">
      <el-form ref="commodityDetailRef" :model="commodityDetail.commodity" label-width="120px" :rules="rules" status-icon
        v-loading="modifySubmitLoading">
        <!-- 商品名称 -->
        <el-form-item prop="commodityName" label="商品名称">
          <el-input input-style="text-align: center;" style="width: 83%;"
            v-model="commodityDetail.commodity.commodityName" />
        </el-form-item>
        <!-- 商品价格 -->
        <el-form-item prop="price" label="商品价格">
          <!-- 利用element-plus的数字输入 -->
          <el-input-number :precision="2" :controls="false" style="width: 83%;" :min="0.01" :max="10000000.00"
            v-model="commodityDetail.commodity.price" />
        </el-form-item>
        <!-- 库存量 -->
        <el-form-item prop="stocks" label="商品库存量">
          <!-- 利用element-plus的数字输入 -->
          <el-input-number :controls="false" style="width: 83%;" v-model="commodityDetail.commodity.stocks" :min="0"
            :max="10000000" />
        </el-form-item>
        <!-- 选择商品类别 -->
        <el-form-item prop="categoryId" label="商品类型">
          <el-tag size="large" style="margin-right: 10px;">{{ selected_category.categoryName }}</el-tag>
          <select-category @confirm="selectCategoryConfirm"></select-category>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-image v-for="item in srcList.map(img_url_pre)"
            style="width: 90px; height: 90px; margin-right: 10px; border-radius: 5px;" :src="item"
            :preview-src-list="srcList.map(img_url_pre)" fit="cover" @dragstart.prevent />
        </el-form-item>
        <!-- 商品描述 -->
        <el-form-item prop="description" label="商品描述">
          <el-input style="width: 83%;" v-model="commodityDetail.commodity.description" :autosize="{ minRows: 4 }"
            type="textarea" />
        </el-form-item>

      </el-form>
      <div style="display: flex; justify-content: center;">
        <el-button type="primary" @click="onSubmit">发起修改</el-button>
        <el-button @click="resetForm(commodityDetailRef)">还原表单</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { getCurrentInstance, onMounted, ref, reactive } from 'vue';
import { commodityPrice, commodityStocks } from '../../../validator'
import SelectCategory from '../../../components/SelectCategory.vue';
import img_url_pre from '../../../utils/img_url_filter';
import { useStore } from 'vuex';

const store = useStore();
const { proxy } = getCurrentInstance();
const manageStoreId = ref("");
const commodityDetailRef = ref();
const commodityList = ref([]);
// 和当前commodityList中的商品相对应
const currentCategoryList = ref([]);
// 控制表格加载遮罩窗是否出现
const loading = ref(false);
// 控制模态框的显示和隐藏
const dialogVisible = ref(false)
let currentDetailIndex = 0;
// 控制分页
const config = reactive({
  total: 0,  // 总的条目数
  current: 1,  // 当前页
  size: 15  // 一页的条目数
})

const selected_category = reactive({
  categoryId: "",
  categoryName: ""
})

const commodityTableLabel = reactive([
  {
    prop: "commodityId",
    label: "商品ID",
    width: 200,
    sortable: true,
  },
  {
    prop: "commodityName",
    label: "商品名称",
    width: 180
  },
  {
    prop: "launchDate",
    label: "上架时间",
    width: 170,
    sortable: true,
  },
  {
    prop: "stocks",
    label: "商品库存量",
    sortable: true,
  }, {
    prop: "salesVolume",
    label: "商品销量",
    sortable: true,
  }
]);

const rules = reactive({
  commodityName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 12, message: '长度应该在1~12个字符之间', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    {
      validator: commodityPrice, trigger: 'blur',
    },
  ],
  stocks: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    {
      validator: commodityStocks, trigger: 'blur',
    },
  ],
  categoryId: [
    { required: true, message: '请选择商品类型', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 1, max: 128, message: '长度应该在1~128个字符之间', trigger: 'blur' },
  ],
})

let commodityDetail = reactive({
  commodity: {
    commodityId: "",
    storeId: "",
    commodityName: "",
    categoryId: "",
    price: 0.0,
    pictures: [],
    description: "",
    salesVolume: 0,
    stocks: 0,
    launchDate: "",
    status: 0
  }
});

let commodityModifyRequest = reactive({
  commodityModifyRequestId: "",
  initiateTime: "",
  processTime: "",
  commodityId: "",
  commodityName: "",
  storeId: "",
  categoryId: "",
  price: 0.0,
  pictures: [],
  description: "",
  stocks: 0,
  status: 0,
  info: ""
})

/**
 * 选择商品的组件确认后的调用
 */
const selectCategoryConfirm = (category) => {
  commodityDetail.commodity.categoryId = category.categoryId;
  selected_category.categoryId = category.categoryId;
  selected_category.categoryName = category.categoryName;
}

// 获取商店的商品列表
const getCommodityList = async (storeId) => {
  // 发起请求
  let res = await proxy.$api.commodity.getCommodityFromStore(storeId, {
    current: config.current,
    size: config.size,
  });
  // 更新表格数据
  commodityList.value = res.data.commodityList
  config.total = res.data.total
  // 遍历并获取商品对应类别名
  currentCategoryList.value = [];
  for (let i = 0; i < commodityList.value.length; ++i) {
    let ret = await proxy.$api.category.getCategory(commodityList.value[i].categoryId);
    currentCategoryList.value.push(ret.data);
  }
};

// 这里直接用索引号找到commodityList中的信息即可
const getCommodityDetail = (index) => {
  commodityDetail.commodity = commodityList.value[index];
  currentDetailIndex = index;
  selected_category.categoryId = currentCategoryList.value[index].categoryId;
  selected_category.categoryName = currentCategoryList.value[index].categoryName;
  // 更新申请详情预览图的srcList
  srcList.value = commodityDetail.commodity.pictures;
}

const changePage = async (page) => {
  loading.value = true;
  // 更新当前页码
  config.current = page
  await getCommodityList(manageStoreId.value)
  loading.value = false;
}

let filterTag = (value, row) => {
  return row.status === value;
}

// 发起商品下架（无需审核）
const offShelf = async (commodity) => {
  let ret = await ElMessageBox.confirm(
    '下架之后只能重新申请上架，你确定要下架该商品吗？',
    '确认下架',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  if (ret === 'confirm') {
    loading.value = true;
    let res = await proxy.$api.commodity.commodityOffShelf(commodity.commodityId);
    if (res.status === 200) {
      // 重新获取一下商品列表
      await getCommodityList(manageStoreId.value);
      ElMessage.success("已成功下架商品");
    }
    loading.value = false;
  }
}

// 重置表单
const resetForm = (formEl) => {
  if (formEl) {
    formEl.resetFields();
    selected_category.categoryId = currentCategoryList.value[currentDetailIndex].categoryId;
    selected_category.categoryName = currentCategoryList.value[currentDetailIndex].categoryName;
  }
}

let modifySubmitLoading = ref(false);

// 提交表单
const onSubmit = async () => {
  let valid = await commodityDetailRef.value.validate();
  if (valid) {
    let ret = await ElMessageBox.confirm(
      '你确定发起商品信息修改吗？',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    if (ret === 'confirm') {
      modifySubmitLoading.value = true;
      // 拷贝
      commodityModifyRequest.commodityId = commodityDetail.commodity.commodityId;
      commodityModifyRequest.commodityName = commodityDetail.commodity.commodityName;
      commodityModifyRequest.storeId = manageStoreId.value;
      commodityModifyRequest.categoryId = commodityDetail.commodity.categoryId;
      commodityModifyRequest.price = commodityDetail.commodity.price;
      commodityModifyRequest.description = commodityDetail.commodity.description;
      commodityModifyRequest.stocks = commodityDetail.commodity.stocks;
      commodityModifyRequest.pictures = commodityDetail.commodity.pictures;
      let res = await proxy.$api.commodity.applyModifyRequest(commodityModifyRequest).catch(error => {
        console.log(error);
        modifySubmitLoading.value = false;
      });
      if (res.status === 200) {
        ElMessage.success({
          showClose: true,
          message: '发起申请成功，管理员通过后修改将生效',
        })
        // 然后清空一下表单
        // TODO
      }
      modifySubmitLoading.value = false;
    }
  } else {
    console.log('表单信息不合法')
  }
}

// 查看申请详情中的图片预览
const srcList = ref([
  "http://dummyimage.com/400x401",
  "http://dummyimage.com/400x402",
  "http://dummyimage.com/400x403",
])

onMounted(async () => {
  manageStoreId.value = store.state.store.manageStoreId
  loading.value = true;
  await getCommodityList(manageStoreId.value);
  loading.value = false;
})
</script>

<style lang="less" scoped>
.table {
  position: relative;
  // height: 520px;

  .pager {
    position: relative;
    bottom: -15px;
    justify-content: flex-end;
    margin-right: 15px;
    margin-top: 10px;
    margin-bottom: 15px;
  }
}

// .commodity-form {}
</style>